<template>
  <div class="content-box">
    <div class="content">
      <div class="group">
        <div class="header">
          <div class="title">智能锁地图</div>
          <div class="handler">
            <div class="showCode">
              <el-switch v-model="showCode" style="--el-switch-on-color: #54bcbd" /><span class="showCodeLabel">显示编码</span>
            </div>
          </div>
        </div>
        <div class="tree">
          <ZTree :id="treeId" :api="getRoomMapTree" :show-code="showCode" @click-dom="zTreeOnClick" />
        </div>
      </div>
      <div class="main">
        <div class="header">
          <div class="title">{{ mapName }}</div>
          <div class="handerBar">
            <el-button type="primary" plain :icon="Notebook" @click="dialogVisible = true">开锁记录</el-button>
          </div>
        </div>
        <div class="table-box" v-loading="loading">
          <SearchForm
            :search="_search"
            :reset="_reset"
            :search-param="searchParam"
            :columns="columns"
            :search-col="{ xs: 1, sm: 1, md: 2, lg: 2, xl: 3 }"
          />
          <div class="roomList" v-if="roomMapList.length">
            <div :class="['room']" v-for="item in roomMapList" :key="item.roomId">
              <div class="door">
                <div class="doorInner">
                  <div class="doorNo">
                    <div v-for="val in item.roomName" :key="val">{{ val }}</div>
                  </div>
                  <!-- <div class="doorHandler"></div> -->
                </div>
              </div>
              <el-button type="primary" link :icon="Unlock" style="color: #ffffff" @click="_unlock(item.roomId)"
                >短时开锁</el-button
              >
            </div>
          </div>
          <div class="noData" v-else>暂无数据</div>
          <div class="footer">
            <Pagination
              :pageable="pageable"
              :handle-size-change="handleSizeChange"
              :handle-current-change="handleCurrentChange"
              :small="true"
            />
          </div>
        </div>
      </div>
    </div>
    <UnlockRecord :dialogVisible="dialogVisible" :handleClose="handleClose" :mapndx="mapid" />
  </div>
</template>

<script setup lang="tsx" name="deviceMonitor">
/* eslint-disable */
// @ts-nocheck
import { ref, provide, nextTick } from "vue";
import { ElMessage, ElLoading } from "element-plus";

import { Unlock, Notebook } from "@element-plus/icons-vue";
import ProTable from "@/components/ProTable/index.vue";
import Pagination from "@/components/ProTable/components/Pagination.vue";
import SearchForm from "@/components/SearchForm/index.vue";
import ZTree from "@/components/ZTree/index.vue";
import UnlockRecord from "./components/UnlockRecord.vue";
import { getRoomMapTree } from "@/api/modules/common";
import { getRoomList, unlock, unlockResult } from "@/api/modules/smartLock/control/smartLockControl";
import { connectStatus } from "@/utils/serviceDict";

const treeId = ref("tree");
const showCode = ref(false);
const loading = ref(false);
const dialogVisible = ref(false);
const mapids = ref([]);
const mapid = ref("");
const mapName = ref("");
const ids = ref([]);
const roomMapList = ref([]);

const enumMap = ref(new Map<string, { [key: string]: any }[]>());
provide("enumMap", enumMap);
enumMap.value.set("onlineStatus", connectStatus);

const columns: any = [
  {
    prop: "clause",
    label: "房间号",
    search: { el: "input" }
  },
  {
    prop: "onlineStatus",
    label: "连接状态",
    search: { el: "select" }
  },
  {
    prop: "electricityMin",
    label: "最小电量",
    search: { el: "input" }
  },
  {
    prop: "electricityMax",
    label: "最大电量",
    search: { el: "input" }
  }
];

const searchParam = ref({
  clause: "",
  onlineStatus: "",
  electricityMin: "",
  electricityMax: ""
});

const pageable = ref({
  pageNum: 1,
  perPageNum: 100,
  total: 0
});

/**
 * 搜索
 */
const _search = () => {
  getRoomFunc();
};

/**
 * 搜索重置
 */
const _reset = () => {
  searchParam.value = {
    clause: "",
    onlineStatus: "",
    electricityMin: "",
    electricityMax: ""
  };
  getRoomFunc();
};

/**
 * 短时开锁
 */
const _unlock = async id => {
  const timeStamp = new Date().getTime();
  try {
    await unlock(ids.value.length ? ids.value : [id]);
    getUnlockResult(id, timeStamp);
  } catch (error) {
    console.log(error);
  }
};

/**
 * 分页页数切换
 */
const handleCurrentChange = val => {
  pageable.value.pageNum = val;
  getRoomFunc();
};

/**
 * 分页条数切换
 */
const handleSizeChange = val => {
  pageable.value.perPageNum = val;
  getRoomFunc();
};

/**
 * 获取房间列表
 */
const getRoomFunc = async () => {
  loading.value = true;
  try {
    const res = await getRoomList({
      mapndxs: mapids.value,
      pageNum: pageable.value.pageNum,
      perPageNum: pageable.value.perPageNum,
      ...searchParam.value
    });
    let { page, records } = res.data;
    loading.value = false;
    pageable.value.total = page.total;
    records = records.map(item => {
      return {
        ...item,
        roomName: item.roomName.indexOf("-") != -1 ? item.roomName.split("-") : [item.roomName]
      };
    });
    roomMapList.value = records;
  } catch (error) {
    loading.value = false;
    console.log(error);
  }
};

/**
 * 获取开锁结果
 */
const getUnlockResult = async (id, timeStamp) => {
  const loadingInstance = ElLoading.service({ fullscreen: true, lock: true, text: "Loading", background: "rgba(0, 0, 0, 0.7)" });
  try {
    const res = await unlockResult({ pageNum: 1, perPageNum: 1, roomId: id, requestStatus: 1 }, true);
    const { records } = res.data;
    if (new Date().getTime() - timeStamp >= 5 * 60 * 1000) {
      ElMessage.success("开锁失败");
      nextTick(() => {
        loadingInstance.close();
      });
      return false;
    }
    if (!records.length) {
      setTimeout(() => {
        getUnlockResult(id, timeStamp);
      }, 30000);
      return false;
    }
    nextTick(() => {
      loadingInstance.close();
    });
    ElMessage.success("开锁成功");
  } catch (error) {
    nextTick(() => {
      loadingInstance.close();
    });
    console.log(error);
  }
};

/**
 * 点击树节点
 */
function zTreeOnClick({ treeNode, ids }) {
  loading.value = true;
  mapid.value = treeNode.id;
  mapName.value = treeNode.name;
  mapids.value = ids;
  pageable.value.pageNum = 1;
  getRoomFunc();
}

/**
 * 关闭弹窗
 */
const handleClose = () => {
  dialogVisible.value = false;
};
</script>
<style scoped lang="scss">
@import "./index.scss";
</style>
